﻿using System;
using HISModels.ViewModel;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Permissions;
using System.Security.Principal;
using System.Web.Security;
using System.Threading;
using KeanuMvc.Reference;
using HIS.Utils.Securities;
using System.IO;
using HIS.Utils;
using HISModels.Entities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Configuration;
using System.Collections;
using System.Collections.ObjectModel;


namespace HIS.Controllers.PatientData {
    public class MedicalRecord : HIS.Controllers.AppBaseController {
        #region Fields
        private string strAction = string.Empty;
        private string strNotification = string.Empty;
        string strUri = string.Empty;
        string strJson = string.Empty;
        private Alergy allergy = null;
        private MedicalFamily medicalFamily = null;
        private MedicalHistories medicalHistories = null;
        private MedicalOccupation occupation = null;
        private Habit habit = null;
        private ProblemList problemList = null;
        private EpisodeDoctorRel episodeRel = null;
        private VPatientData patient = null;
        private string patientId = string.Empty;
        private string doctorId = string.Empty;
        private StringReader stringReader = null;
        private DataTablesNet paging = null;
        string aaData = string.Empty;
        #endregion

        public MedicalRecord() {
            try {
                doctorId = HIS.Utils.Helper.GetDoctorId();
                Data.Add("docid", doctorId);
                Data.Add("NotificationAllergiesView", strNotification);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [Authorization(RoleAction = "patient-medicalrecord")]
        public override void Index() {
            try {
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            } finally {
                RenderFile("Patient\\medicationrecord.html");
            }
        }

        [Authorization(RoleAction = "patient-medicalrecord")]
        public void ViewPatientData() {
            try {
                Data.Add("Pagetitle", "View Patient Data");
                HttpContext.Current.Session["patientId"] = KeanuMvc.Reference.CryptoString.Decrypt(HttpContext.Current.Request["id"].NullSafeToString().Trim());
                Data.Add("PatientId", HttpContext.Current.Session["patientId"]);

                string strUri = Global.ServiceUriDictionary["patient"] + HttpContext.Current.Session["patientId"] + Global.ServiceUriDictionary["requestformat"];


                stringReader = base.RestService.GetJson(strUri);

                patient = JsonConvert.DeserializeObject<VPatientData>(stringReader.ReadToEnd());
                Utils.Helper.SetNullToEmptyString(patient);

                Data.Add("MRNo", patient.Patient.MedicalRecordNumber);
                Data.Add("PatientName", patient.Patient.FirstName + " " + patient.Patient.MiddleName + " " + patient.Patient.LastName);
                string age = string.Empty;
                if (patient.Patient.Birthdate != null)
                    age = Utils.Helper.GetAge(patient.Patient.Birthdate);
                Data.Add("Age", age.NullSafeToString());
                Data.Add("Gender", patient.Patient.GenderId == 1 ? "Male" : "Female");
                Data.Add("Weight", patient.Patient.Weight.NullSafeToString());
                Data.Add("Height", patient.Patient.Height.NullSafeToString());
                Data.Add("Room", "");  //waiting for relations

                RenderFile("Patient\\viewpatientdata.html");
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }


        #region Tab allergies
        [Authorization(RoleAction = "patient-medicalrecord")]
        public void TableListAllergies() {
            try {
                string patientid = HttpContext.Current.Session["patientId"].NullSafeToString();

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                pagingSearch.sSearch = "patientid=" + patientid;

                strUri = Global.ServiceUriDictionary["mralergiespaging"] + Global.ServiceUriDictionary["requestformat"];

                ///Post paging object to rest as json string///
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));
                strJson = stringReader.ReadToEnd();
                HttpContext.Current.Response.Write(strJson);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [Authorization(RoleAction = "patient-medicalrecord")]
        public void SaveAllergies() {
            try {
                strUri = Global.ServiceUriDictionary["medicalrecord"] + HttpContext.Current.Session["patientId"] + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.GetJson(strUri);

                episodeRel = JsonConvert.DeserializeObject<HISModels.Entities.EpisodeDoctorRel>(stringReader.ReadToEnd());

                allergy = new Alergy();
                Utils.Helper.SetNullToEmptyString(allergy);
                allergy.PostHandler<HISModels.Entities.Alergy>();
                allergy.AlergiesTo = HttpContext.Current.Request["allergies-to"];
                allergy.Brand = HttpContext.Current.Request["brand-allergies-view"];
                allergy.IsGeneric = HttpContext.Current.Request["generic-allergies-view"];
                allergy.DescValue = HttpContext.Current.Request["description-allergies-view"];
                allergy.IsSubjective = Convert.ToInt32(HttpContext.Current.Request["is-subjective-allergies"]);
                allergy.RecordStatus = 0;
                allergy.RecordTime = DateTime.Now;
                allergy.EpisodeDoctorRelId = episodeRel.Id;
                strUri = Global.ServiceUriDictionary["mralergies"].Trim() + Global.ServiceUriDictionary["requestformat"];

                stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(allergy));
            } catch (Exception ex) {
                strNotification = ex.Message;
            } finally {
                HttpContext.Current.Response.Write(strNotification);
            }
        }

        [Authorization(RoleAction = "patient-medicalrecord")]
        public void UpdateAllergy() {

        }

        #endregion

        #region Tab Family History
        [Authorization(RoleAction = "patient-medicalrecord")]
        public void TableListFamilyHistory() {
            try {
                string patientid = HttpContext.Current.Session["patientId"].NullSafeToString();

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                pagingSearch.sSearch = "patientid=" + patientid;

                strUri = Global.ServiceUriDictionary["mrmedfampaging"] + Global.ServiceUriDictionary["requestformat"];

                ///Post paging object to rest as json string///
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));
                strJson = stringReader.ReadToEnd();
                HttpContext.Current.Response.Write(strJson);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [Authorization(RoleAction = "patient-medicalrecord")]
        public void SaveFamilyHistory() {
            try {

                strUri = Global.ServiceUriDictionary["medicalrecord"] + HttpContext.Current.Session["patientId"] + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.GetJson(strUri);

                episodeRel = JsonConvert.DeserializeObject<HISModels.Entities.EpisodeDoctorRel>(stringReader.ReadToEnd());

                medicalFamily = new MedicalFamily();
                Utils.Helper.SetNullToEmptyString(medicalFamily);
                medicalFamily.PostHandler<HISModels.Entities.MedicalFamily>();
                medicalFamily.DiseaseHistory = HttpContext.Current.Request["diseasehistory-family"].NullSafeToString();
                medicalFamily.Relations = HttpContext.Current.Request["relations"].NullSafeToString();
                medicalFamily.RecordStatus = 0;
                medicalFamily.RecordTime = DateTime.Now;
                medicalFamily.EpisodeDoctorRelId = episodeRel.Id;
                strUri = Global.ServiceUriDictionary["mrmedfam"] + Global.ServiceUriDictionary["requestformat"];

                stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(medicalFamily));

            } catch (Exception ex) {
                strNotification = ex.Message;
            } finally {
                base.RestService.Dispose();
            }
        }
        #endregion

        #region Tab Medical History

        [Authorization(RoleAction = "patient-medicalrecord")]
        public void SaveMedicalHistory() {
            try {
                strUri = Global.ServiceUriDictionary["medicalrecord"] + HttpContext.Current.Session["patientId"] + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.GetJson(strUri);

                episodeRel = JsonConvert.DeserializeObject<HISModels.Entities.EpisodeDoctorRel>(stringReader.ReadToEnd());

                medicalHistories = new MedicalHistories();
                Utils.Helper.SetNullToEmptyString(medicalHistories);
                medicalHistories.PostHandler<HISModels.Entities.MedicalHistories>();
                medicalHistories.DiseaseHistory = HttpContext.Current.Request["diseasehistory-medical"];
                medicalHistories.Year = Convert.ToInt32(HttpContext.Current.Request["year"]);
                medicalHistories.RecordStatus = 0;
                medicalHistories.RecordTime = DateTime.Now;
                medicalHistories.EpisodeDoctorRelId = episodeRel.Id;
                strUri = Global.ServiceUriDictionary["mrmedhistory"].Trim() + Global.ServiceUriDictionary["requestformat"];

                stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(medicalHistories));
            } catch (Exception ex) {
                strNotification = ex.Message;
            } finally {
                HttpContext.Current.Response.Write(strNotification);
            }
        }

        [Authorization(RoleAction = "patient-medicalrecord")]
        public void TableListMedicalHistory() {
            try {
                string patientid = HttpContext.Current.Session["patientId"].NullSafeToString();

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                pagingSearch.sSearch = "patientid=" + patientid;

                strUri = Global.ServiceUriDictionary["mrmedhistorypaging"] + Global.ServiceUriDictionary["requestformat"];

                ///Post paging object to rest as json string///
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));
                strJson = stringReader.ReadToEnd();
                HttpContext.Current.Response.Write(strJson);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }
        #endregion

        #region Tab Habits
        [Authorization(RoleAction = "patient-medicalrecord")]
        public void SaveHabits() {
            try {

                strUri = Global.ServiceUriDictionary["medicalrecord"] + HttpContext.Current.Session["patientId"] + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.GetJson(strUri);

                episodeRel = JsonConvert.DeserializeObject<HISModels.Entities.EpisodeDoctorRel>(stringReader.ReadToEnd());

                habit = new Habit();
                Utils.Helper.SetNullToEmptyString(habit);
                habit.PostHandler<HISModels.Entities.Habit>();
                habit.Description = HttpContext.Current.Request["habit-description"].NullSafeToString();
                habit.Quantity = HttpContext.Current.Request["quantity"].NullSafeToString();
                habit.Duration = HttpContext.Current.Request["duration"].NullSafeToString();
                habit.RecordStatus = 0;
                habit.RecordTime = DateTime.Now;
                habit.EpisodeDoctorRelId = episodeRel.Id;
                strUri = Global.ServiceUriDictionary["mrhabit"] + Global.ServiceUriDictionary["requestformat"];

                stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(habit));

            } catch (Exception ex) {
                strNotification = ex.Message;
            } finally {
                base.RestService.Dispose();
            }
        }

        [Authorization(RoleAction = "patient-medicalrecord")]
        public void TableListHabits() {
            try {
                string patientid = HttpContext.Current.Session["patientId"].NullSafeToString();

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                pagingSearch.sSearch = "patientid=" + patientid;

                strUri = Global.ServiceUriDictionary["mrhabitpaging"] + Global.ServiceUriDictionary["requestformat"];

                ///Post paging object to rest as json string///
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));
                strJson = stringReader.ReadToEnd();
                HttpContext.Current.Response.Write(strJson);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }
        #endregion

        #region Tab Occupation
        
        #endregion

        #region Tab Problem List
        [Authorization(RoleAction = "patient-medicalrecord")]
        public void SaveProblemList() {
            try {

                strUri = Global.ServiceUriDictionary["medicalrecord"] + HttpContext.Current.Session["patientId"] + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.GetJson(strUri);

                episodeRel = JsonConvert.DeserializeObject<HISModels.Entities.EpisodeDoctorRel>(stringReader.ReadToEnd());

                problemList = new ProblemList();
                Utils.Helper.SetNullToEmptyString(problemList);
                problemList.PostHandler<HISModels.Entities.ProblemList>();
                problemList.ProblemRecords = HttpContext.Current.Request["problem-list-description"].NullSafeToString();
                problemList.RecordStatus = 0;
                problemList.RecordTime = DateTime.Now;
                problemList.EpisodeDoctorRelId = episodeRel.Id;
                strUri = Global.ServiceUriDictionary["mrprobleml"] + Global.ServiceUriDictionary["requestformat"];

                stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(problemList));

            } catch (Exception ex) {
                strNotification = ex.Message;
            } finally {
                base.RestService.Dispose();
            }
        }

        [Authorization(RoleAction = "patient-medicalrecord")]
        public void TableListProblemList() {
            try {
                string patientid = HttpContext.Current.Session["patientId"].NullSafeToString();

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                pagingSearch.sSearch = "patientid=" + patientid;

                strUri = Global.ServiceUriDictionary["mrproblemlpaging"] + Global.ServiceUriDictionary["requestformat"];

                ///Post paging object to rest as json string///
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));
                strJson = stringReader.ReadToEnd();
                HttpContext.Current.Response.Write(strJson);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }
        #endregion

        #region Private Functions
        private static string emptyDataTable(IList list) {
            string emptyDt = string.Empty;
            DataTablesNet paging = new DataTablesNet();
            paging.sEcho = 1;
            paging.aaData = list.AsQueryable();
            return emptyDt = JsonConvert.SerializeObject(paging);

        }
        #endregion
    }
}